<template>
	<view class="add-address">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 地址搜索区域 -->
		<view class="map-container">
			<map
				id="addressMap"
				class="map"
				:latitude="latitude"
				:longitude="longitude"
				:markers="markers"
				:scale="16"
				show-location
				@regionchange="onMapRegionChange"
			></map>
			<view class="search-box">
				<view class="search-input">
					<text class="search-icon">🔍</text>
					<input 
						type="text" 
						placeholder="搜索地址" 
						v-model="searchText"
						@input="onSearchInput"
					/>
				</view>
			</view>
			
			<!-- 搜索结果列表 -->
			<view class="search-results" v-if="searchResults.length > 0">
				<view 
					class="result-item" 
					v-for="(item, index) in searchResults" 
					:key="index"
					@tap="selectSearchResult(item)"
				>
					<view class="title">{{ item.title }}</view>
					<view class="address">{{ item.address }}</view>
				</view>
			</view>
		</view>
		
		<!-- 表单区域 -->
		<view class="form-section">
			<view class="form-item">
				<text class="label required">所在地区</text>
				 <div @click="changeAddress">
				      {{ address ? address : "点击选择省市区" }}
				    </div>
				    <Address :value="province+city+district" @confirm="confirmAddress" ref="address"></Address>
			</view>
			
			<view class="form-item">
				<text class="label required">服务地址与门牌号</text>
				<input type="text" placeholder="填写服务地址" v-model="addressDetail" />
			</view>
			
			<view class="form-item">
				<text class="label required">联系人姓名</text>
				<input type="text" placeholder="填写联系人姓名" v-model="receiverName" />
			</view>
			
			<view class="form-item">
				<text class="label required">手机号</text>
				<view class="phone-input">
					<text class="area-code" @tap="showAreaCodePicker">+86</text>
					<input type="number" placeholder="填写手机号码" v-model="phone" />
				</view>
			</view>
		</view>
		
		<!-- 地址标签 -->
		<view class="tag-section">
			<text class="section-title">服务标签</text>
			<view class="tag-list">
				<view 
					class="tag-item" 
					v-for="(tag, index) in tags" 
					:key="index"
					:class="{ active: selectedTag === tag }"
					@tap="selectTag(tag)"
				>{{ tag }}</view>
			</view>
		</view>
		
		<!-- 保存按钮 -->
		<button class="save-btn" @tap="saveAddress">保存服务地址</button>
	</view>
</template>

<script>
import Address from "@/components/address.vue";
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
	data() {
		return {
			latitude: 39.908692,
			longitude: 116.397477,
			currentAddress: '',
			searchText: '',
			searchResults: [],
			selectedArea: '',
			addressDetail: '',
			receiverName: '',
			phone: '',
			markers: [{
				id: 1,
				latitude: 39.908692,
				longitude: 116.397477,
				width: 40,
				height: 40,
				iconPath: '/static/icons/location.png'
			}],
			tags: ['家', '公司', '学校', '父母', '朋友'],
			selectedTag: '',
			province: '',
			city: '',
			district: '',
			searchTimer: null,
			address: "",
			isEdit: false,
			addressId: null,
			// 腾讯地图API配置
			tencentMapKey: 'GJZBZ-5ZV6G-ID2QK-Q6ODP-WNIPQ-HZFB4', // 替换为您的腾讯地图API密钥
			// 移除微信JSSDK相关配置
			isWeixin: false,
			jWeixin: null,
			// 后端代理API路径
			proxyApiUrl: `${uni.$config.baseUrl}/map`,
			isIOS: false
		}
	},
	components: {
	    Address,
	  },
	onLoad(options) {
		// iOS 首次进入自动刷新
		// this.isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
		// if (this.isIOS && !sessionStorage.getItem('iosRefreshed_editAddress')) {
		// 	sessionStorage.setItem('iosRefreshed_editAddress', 'true');
		// 	window.location.reload();
		// 	return;
		// }
		// 设置导航栏标题
		uni.setNavigationBarTitle({
			title: options.addressInfo ? '编辑服务地址' : '新增服务地址'
		})
		
		// 检查是否在微信环境中
		this.isWeixin = /MicroMessenger/i.test(navigator.userAgent)
		
		// 如果是编辑地址，获取传递过来的地址信息
		if (options.addressInfo) {
			const address = JSON.parse(decodeURIComponent(options.addressInfo))
			this.receiverName = address.recipientName
			this.phone = address.recipientPhone
			this.addressDetail = address.detailAddress
			this.selectedTag = address.tag || ''
			this.addressId = address.id
			this.isEdit = true
			
			// Set province, city, district and address
			this.province = address.province || ''
			this.city = address.city || ''
			this.district = address.district || ''
			this.address = address.province && address.city && address.district ? 
				`${address.province} ${address.city} ${address.district}` : ''
			
			if (address.latitude && address.longitude) {
				this.latitude = address.latitude
				this.longitude = address.longitude
				this.markers[0].latitude = address.latitude
				this.markers[0].longitude = address.longitude
			}
		}
		
		// 获取当前位置
		if(!options.addressInfo){
			this.getCurrentLocation()
		}
	},
	onShow() {
		},
	methods: {
		// 获取当前位置
		async getCurrentLocation() {
			try {
				// 获取当前页面URL
				const currentUrl = window.location.href.split('#')[0]
				
				// 获取jssdk配置
				const configRes = await uni.request({
					url: `${uni.$config.baseUrl}/wx/jssdk/config`,
					method: 'GET',
					data: {
						url: currentUrl
					}
				})
				
				if (configRes.statusCode === 200 && configRes.data.code === 200) {
					const config = configRes.data.data
					
					// 加载jweixin-module
					this.jWeixin = require('jweixin-module')
					
					// 配置微信JSSDK
					this.jWeixin.config({
						debug: false,
						appId: config.appId,
						timestamp: config.timestamp,
						nonceStr: config.nonceStr,
						signature: config.signature,
						jsApiList: ['getLocation', 'openLocation']
					})
					
					// 使用微信JSSDK获取位置
					this.jWeixin.ready(() => {
						this.jWeixin.getLocation({
							type: 'gcj02',
							success: (res) => {
								console.log('微信定位成功:', res)
								
								// 更新地图位置和标记
								this.latitude = res.latitude
								this.longitude = res.longitude
								this.markers[0].latitude = res.latitude
								this.markers[0].longitude = res.longitude
								
								// 使用逆地址解析获取详细地址
								this.getAddressFromLocation(res.latitude, res.longitude)
							},
							fail: () => {
								console.error('微信定位失败')
								// 如果微信定位失败，尝试使用IP定位
								this.getLocationByIP()
							}
						})
					})
					
					this.jWeixin.error((err) => {
						console.error('微信JSSDK配置失败:', err)
						// 如果微信JSSDK配置失败，尝试使用IP定位
						this.getLocationByIP()
					})
				} else {
					console.error('获取JSSDK配置失败')
					// 如果获取配置失败，尝试使用IP定位
					this.getLocationByIP()
				}
			} catch (error) {
				console.error('加载jweixin-module失败:', error)
				// 如果加载jweixin-module失败，尝试使用IP定位
				this.getLocationByIP()
			}
		},
		
		// 使用IP定位
		getLocationByIP() {
			// 使用腾讯地图IP定位API获取位置
			uni.request({
				url: `${this.proxyApiUrl}/location/v1/ip`,
				data: {
					key: this.tencentMapKey,
					output: 'json'
				},
				success: (res) => {
					if (res.data.code === 200) {
						const location = res.data.data.location;
						this.latitude = location.lat;
						this.longitude = location.lng;
						this.markers[0].latitude = location.lat;
						this.markers[0].longitude = location.lng;
						
						// 使用逆地址解析获取详细地址
						this.getAddressFromLocation(location.lat, location.lng);
					} else {
						console.error('IP定位失败:', res.data);
						// 定位失败，使用默认位置（北京）
						this.useDefaultLocation();
					}
				},
				fail: (err) => {
					console.error('请求IP定位失败:', err);
					// 请求失败，使用默认位置（北京）
					this.useDefaultLocation();
				}
			});
		},
		
		// 使用默认位置（北京）
		useDefaultLocation() {
			this.latitude = 39.908692;
			this.longitude = 116.397477;
			this.markers[0].latitude = 39.908692;
			this.markers[0].longitude = 116.397477;
			
			// 使用逆地址解析获取详细地址
			this.getAddressFromLocation(this.latitude, this.longitude);
		},
		
		// 监听地图拖动
		onMapRegionChange(e) {
			if (e.type === 'end' && e.causedBy === 'drag') {
				// 获取地图中心点位置
				const mapContext = uni.createMapContext('addressMap')
				mapContext.getCenterLocation({
					success: (res) => {
						this.latitude = res.latitude
						this.longitude = res.longitude
						// 更新标记点位置
						this.markers[0].latitude = res.latitude
						this.markers[0].longitude = res.longitude
						
						// 使用逆地址解析获取详细地址
						this.getAddressFromLocation(res.latitude, res.longitude)
					}
				})
			}
		},
		
		// 搜索输入处理（防抖）
		onSearchInput() {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			
			if (!this.searchText.trim()) {
				this.searchResults = []
				return
			}
			
			this.searchTimer = setTimeout(() => {
				this.searchAddress()
			}, 500)
		},
		
		// 搜索地址
		searchAddress() {
			// 通过后端代理请求腾讯地图地点搜索API
			uni.request({
				url: `${this.proxyApiUrl}/place/v1/search`,
				data: {
					keyword: this.searchText,
					boundary: `nearby(${this.latitude},${this.longitude},1000)`,
					key: this.tencentMapKey,
					page_size: 10,
					page_index: 1,
					output: 'json'
				},
				success: (res) => {
					if (res.data.code === 200) {
						// 处理搜索结果
						this.searchResults = res.data.data.map(item => {
							return {
								title: item.title,
								address: item.address,
								latitude: item.location.lat,
								longitude: item.location.lng,
								province: item.ad_info.province,
								city: item.ad_info.city,
								district: item.ad_info.district
							}
						})
					} else {
						console.error('搜索地址失败:', res.data)
						uni.showToast({
							title: '搜索地址失败',
							icon: 'none'
						})
					}
				},
				fail: (err) => {
					console.error('请求搜索地址失败:', err)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 选择搜索结果
		selectSearchResult(item) {
			// 更新地图位置和标记
			this.latitude = item.latitude
			this.longitude = item.longitude
			this.markers[0].latitude = item.latitude
			this.markers[0].longitude = item.longitude
			
			// 更新地址信息
			this.province = item.province
			this.city = item.city
			this.district = item.district
			this.address = `${this.province} ${this.city} ${this.district}`
			this.addressDetail = item.title
			
			// 清空搜索结果和搜索框
			this.searchResults = []
			this.searchText = ''
			
			// 移动地图到选中位置
			const mapContext = uni.createMapContext('addressMap')
			mapContext.moveToLocation({
				latitude: item.latitude,
				longitude: item.longitude
			})
		},
		
		// 解析地址
		parseAddress(address) {
			// 匹配省市区
			const provinceReg = /(.*?省|.*?自治区|北京市|天津市|上海市|重庆市)/
			const cityReg = /(.*?市|.*?自治州|.*?地区|.*?盟)/
			const districtReg = /(.*?区|.*?县|.*?旗|.*?市)/
			
			let province = address.match(provinceReg)
			let city = address.match(cityReg)
			let district = address.match(districtReg)
			
			let selectedArea = ''
			if (province) selectedArea += province[1]
			if (city) selectedArea += city[1]
			if (district) selectedArea += district[1]
			
			this.selectedArea = selectedArea
		},
		
		// 获取地址坐标
		getCoordinatesFromAddress(address) {
			// 通过后端代理请求腾讯地图地理编码API
			uni.request({
				url: `${this.proxyApiUrl}/geocoder/v1/`,
				data: {
					address: address,
					key: this.tencentMapKey,
					output: 'json'
				},
				success: (res) => {
					if (res.data.code === 200) {
						const location = res.data.data.location
						// 更新地图位置和标记
						this.latitude = location.lat
						this.longitude = location.lng
						this.markers[0].latitude = location.lat
						this.markers[0].longitude = location.lng
						
						// 移动地图到新位置
						const mapContext = uni.createMapContext('addressMap')
						mapContext.moveToLocation({
							latitude: location.lat,
							longitude: location.lng
						})
					} else {
						console.error('地理编码失败:', res.data)
						uni.showToast({
							title: '获取地址坐标失败',
							icon: 'none'
						})
					}
				},
				fail: (err) => {
					console.error('请求地理编码失败:', err)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 根据经纬度获取地址信息
		getAddressFromLocation(latitude, longitude) {
			// 通过后端代理请求腾讯地图逆地址解析API
			uni.request({
				url: `${this.proxyApiUrl}/geocoder/v1/`,
				data: {
					location: `${latitude},${longitude}`,
					key: this.tencentMapKey,
					output: 'json'
				},
				success: (res) => {
					if (res.data.code === 200) {
						const addressComponent = res.data.data.ad_info
						// 更新省市区信息
						this.province = addressComponent.province
						this.city = addressComponent.city
						this.district = addressComponent.district
						this.address = `${this.province} ${this.city} ${this.district}`
						
						// 更新详细地址
						this.addressDetail = res.data.data.address
					} else {
						console.error('逆地址解析失败:', res.data)
					}
				},
				fail: (err) => {
					console.error('请求逆地址解析失败:', err)
				}
			})
		},
		
		changeAddress() {
			this.$refs.address.open();
		},
		
		confirmAddress(val) {
			console.log(val, "eee");
			// Split the address into components
			const addressParts = val.split(' ');
			if (addressParts.length >= 3) {
				this.province = addressParts[0];
				this.city = addressParts[1];
				this.district = addressParts[2];
			}
			this.address = val;
			this.selectedArea = val.replace(/\s/g, ''); // Remove spaces for display
			this.$refs.address.cancel();
			
			// Get coordinates for the selected address
			this.getCoordinatesFromAddress(this.selectedArea);
		},
		
		showAreaPicker() {
			// 实现省市区选择器
			uni.showToast({
				title: '打开地区选择器',
				icon: 'none'
			})
		},
		
		showAreaCodePicker() {
			// 实现国际区号选择器
			uni.showToast({
				title: '打开区号选择器',
				icon: 'none'
			})
		},
		
		selectTag(tag) {
			this.selectedTag = tag
		},
		
		saveAddress() {
			// 验证必填字段
			if (!this.address) {
				uni.showToast({
					title: '请选择所在地区',
					icon: 'none'
				})
				return
			}
			if (!this.addressDetail) {
				uni.showToast({
					title: '请填写服务地址',
					icon: 'none'
				})
				return
			}
			if (!this.receiverName) {
				uni.showToast({
					title: '请填写联系人姓名',
					icon: 'none'
				})
				return
			}
			if (!this.phone) {
				uni.showToast({
					title: '请填写手机号',
					icon: 'none'
				})
				return
			}
			
			// 手机号格式验证（中国大陆 11 位手机号）
			const phoneRegex = /^1[3-9]\d{9}$/
			if (!phoneRegex.test(this.phone)) {
				uni.showToast({
					title: '手机号格式不正确',
					icon: 'none'
				})
				return
			}
			
			// 获取用户ID
			const userInfoStr = uni.getStorageSync('userInfo')
			if (!userInfoStr) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				return
			}
			
			let userInfo;
			try {
				// 尝试解析用户信息
				userInfo = typeof userInfoStr === 'string' ? JSON.parse(userInfoStr) : userInfoStr;
				
				// 检查是否是登录响应格式
				if (userInfo.code === 200 && userInfo.data) {
					userInfo = userInfo.data;
				}
			} catch (e) {
				console.error('解析用户信息失败', e);
				uni.showToast({
					title: '用户信息格式错误',
					icon: 'none'
				});
				return;
			}
			
			// 构造地址信息
			const memberAddress = {
				userId: userInfo.memberId,
				recipientName: this.receiverName,
				recipientPhone: this.phone,
				province: this.province || '',
				city: this.city || '',
				district: this.district || '',
				detailAddress: this.addressDetail,
				fullAddress: this.address + this.addressDetail,
				tag: this.selectedTag,
				latitude: this.latitude,
				longitude: this.longitude
			}
			
			// 如果是编辑模式，添加地址ID
			if (this.isEdit) {
				memberAddress.id = this.addressId
			}
			
			// 根据是否为编辑模式选择不同的API请求方法
			const requestMethod = this.isEdit ? 'PUT' : 'POST'
			
			// 调用API
			uni.request({
				url: `${uni.$config.baseUrl}/address/address`,
				method: requestMethod,
				data: memberAddress,
				header: {
					'content-type': 'application/json'
				},
				success: (res) => {
					if (res.statusCode === 200 && res.data.code === 200) {
						// 先显示成功提示
						uni.showToast({
							title: this.isEdit ? '修改成功' : '保存成功',
							icon: 'success',
							duration: 1500
						});
						
						// 直接返回上一页，不等待提示显示完成
						setTimeout(() => {
							uni.navigateBack({ delta: 1 });
						}, 500);
					} else {
						uni.showToast({
							title: res.data.msg || (this.isEdit ? '修改失败' : '保存失败'),
							icon: 'none'
						})
					}
				},
				fail: (err) => {
					console.error(this.isEdit ? '修改地址失败:' : '保存地址失败:', err)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				}
			})
		}
	}
}
</script>

<style lang="scss">
	.content {
	  display: flex;
	  flex-direction: column;
	  gap: 40rpx;
	  padding: 40rpx;
	}
.add-address {
	min-height: 100vh;
	background: #F8F8F8;
	padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
	
	.map-container {
		background: #FFFFFF;
		position: relative;
		
		.current-location {
			padding: 20rpx;
			font-size: 28rpx;
			color: #333;
			border-bottom: 1rpx solid #EEEEEE;
		}
		
		.map {
			width: 100%;
			height: 400rpx;
		}
		
		.search-box {
			display: flex;
			align-items: center;
			padding: 20rpx;
			gap: 20rpx;
			
			.search-input {
				flex: 1;
				display: flex;
				align-items: center;
				background: #F5F5F5;
				padding: 15rpx 20rpx;
				border-radius: 8rpx;
				
				.search-icon {
					margin-right: 10rpx;
					color: #999;
				}
				
				input {
					flex: 1;
					font-size: 28rpx;
					background-color: transparent;
				}
			}
			
			.paste-btn {
				font-size: 28rpx;
				color: #333;
			}
		}
		
		.search-results {
			position: absolute;
			top: 100%;
			left: 0;
			right: 0;
			background: #FFFFFF;
			max-height: 600rpx;
			overflow-y: auto;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
			z-index: 100;
			
			.result-item {
				padding: 20rpx;
				border-bottom: 1rpx solid #EEEEEE;
				
				&:active {
					background: #F5F5F5;
				}
				
				.title {
					font-size: 28rpx;
					color: #333333;
					margin-bottom: 8rpx;
				}
				
				.address {
					font-size: 24rpx;
					color: #666666;
				}
			}
		}
	}
	
	.form-section {
		margin-top: 20rpx;
		background: #FFFFFF;
		
		.form-item {
			display: flex;
			align-items: center;
			padding: 30rpx 20rpx;
			border-bottom: 1rpx solid #EEEEEE;
			
			.label {
				width: 200rpx;
				font-size: 28rpx;
				color: #333;
				
				&.required::before {
					content: '*';
					color: #FF0000;
					margin-right: 4rpx;
				}
			}
			
			input {
				flex: 1;
				font-size: 28rpx;
			}
			
			.arrow {
				color: #999;
				margin-left: 10rpx;
			}
			
			.btn {
				font-size: 28rpx;
				color: #666;
			}
			
			.phone-input {
				flex: 1;
				display: flex;
				align-items: center;
				
				.area-code {
					font-size: 28rpx;
					color: #333;
					margin-right: 20rpx;
				}
			}
		}
	}
	
	.tag-section {
		margin-top: 20rpx;
		background: #FFFFFF;
		padding: 20rpx;
		
		.section-title {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 20rpx;
		}
		
		.tag-list {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			
			.tag-item {
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				font-size: 28rpx;
				color: #666;
				background: #F5F5F5;
				
				&.active {
					color: #FFFFFF;
					background: #00B26A;
				}
				
				&.custom {
					border: 1rpx dashed #999;
					background: #FFFFFF;
				}
			}
		}
	}
	
	.save-btn {
		position: fixed;
		left: 20rpx;
		right: 20rpx;
		bottom: 40rpx;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		background: #00B26A;
		color: #FFFFFF;
		font-size: 32rpx;
		border-radius: 44rpx;
		
		&:active {
			opacity: 0.9;
		}
	}
}
</style> 